<?php
/**
 * 注册验证器
 */
namespace app\api\validate;

use think\Validate;
use think\Db;

class RegisterValidate extends Validate
{
    protected $rule = [
        'mobile'     => ['require', 'regex' => '^1[34578]\d{9}$', 'checkMobile'],
        'invitation' => ['regex' => '^1[34578]\d{9}$'],
        'password'   => ['require', 'regex' => '^(\w*(?=\w*\d)(?=\w*[A-Za-z])\w*){6,16}$'],
        'second_password' => ['require', 'regex' => '^(\w*(?=\w*\d)(?=\w*[A-Za-z])\w*){6,16}$', 'checkRepeat'],
        'code'       => 'require|number|checkCode',
        'province'   => 'require|between:1,34',
        'city'       => 'require',
        'area'       => 'require|checkArea',
    ];

    protected $message = [
        'mobile.require' => '手机号码必须',
        'mobile.regex' => '手机号码格式错误',
        'invitation.regex' => '邀请人手机号码格式错误',
        'password.require' => '密码必须',
        'password.regex' => '密码要6-16（英文/数字/符号）至少两种或下划线组合',
        'code.require' => '验证码必须',
        'code.number' => '验证码必须是数字',
        'province.require' => '省必须选',
        'province.between' => '省选择错误',
        'city.require' => '市必须选',
        'area.require' => '区必须选',
    ];
    /**
     * 验证手机
     */
    public function checkMobile($value, $rule ,$data)
    {
    	$is_has = Db::name('shop_user')->where('user_name', $data['mobile'])->find();
    	if (empty($is_has)) {
    		return true;
    	}
    	return '该手机号已经注册';
    }
    /**
     * 验证地区
     */
    public function checkArea($value, $rule ,$data)
    {
    	
    	$is_has = Db::name('region')->alias('a')
    			->field('a.*,b.parent_id as grandpa_id')
				->join('region b', 'a.parent_id=b.id', 'left')
				->where(['a.id' => $data['area'], 'a.parent_id' => $data['city'], 'b.parent_id' => $data['province']])
				->find();
	
		if (empty($is_has)) {
			return '请选择正确的地址';
		}
		return true;
    }
    /**
     * 验证密码是否一致
     */
    public function checkRepeat($value, $rule ,$data)
    {
    	if ($data['password'] != $data['second_password']) {
    		return '两次密码不一致';
    	}
    	return true;
    }
    /**
     * 验证验证码
     */
    public function checkCode($value, $rule ,$data)
    {
    	$info = Db::name('sms_validate')->where(['mobile' => $data['mobile'], 'code' => $data['code']])->order('id DESC')->find();
    	if (empty($info)) {
    		return '验证码不存在';
    	}
    	if ($info['expire_time'] < time()) {
    		return '验证码过期';
    	}
    	return true;
    }
}